# v0.3-main.py 
import sys
import argparse
import re
import os

#莱文斯坦距离函数，用于智能建议异常处理模块
def levenshtein_distance(s1, s2):
    """计算两个字符串之间的莱文斯坦编辑距离"""
    if len(s1) < len(s2):
        return levenshtein_distance(s2, s1)
    if len(s2) == 0:
        return len(s1)
    previous_row = range(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row
    return previous_row[-1]

def analyze_code_content(content, file_path):
    _, extension = os.path.splitext(file_path)
    is_c_language = extension.lower() == '.c'
    lines = content.splitlines()
    results = { "total": len(lines), "code": 0, "blank": 0, "comment": 0 }
    in_c_multiline_comment = False
    in_py_multiline_comment = False
    py_comment_delimiter = None
    for line in lines:
        stripped = line.strip()
        if not stripped:
            results["blank"] += 1
            continue
        if in_c_multiline_comment:
            results["comment"] += 1
            if '*/' in stripped: in_c_multiline_comment = False
            continue
        if in_py_multiline_comment:
            results["comment"] += 1
            if py_comment_delimiter in stripped: in_py_multiline_comment = False
            continue
        is_comment_line = False
        if stripped.startswith('//'):
            is_comment_line = True
        elif stripped.startswith('#'):
            if not is_c_language:
                is_comment_line = True
        if is_comment_line:
            results["comment"] += 1
            continue
        if stripped.startswith('/*'):
            results["comment"] += 1
            if '*/' not in stripped: in_c_multiline_comment = True
            continue
        if stripped.startswith('"""') or stripped.startswith("'''"):
            if not is_c_language:
                results["comment"] += 1
                delimiter = '"""' if stripped.startswith('"""') else "'''"
                if stripped.count(delimiter) < 2:
                    in_py_multiline_comment = True
                    py_comment_delimiter = delimiter
                continue
        results["code"] += 1
    return results

#基础功能函数
def count_chars(content): return len(content)
def count_words(content): return len(content.split())
def count_sentences(content): return len(re.findall(r'(?:[.!?]+)(?:\s|$)', content))

def main():
    parser = argparse.ArgumentParser(description="Intelligent command-line text & code analyzer v0.3 Final")
    parser.add_argument('file', help="输入文件路径")
    basic_group = parser.add_argument_group('Basic Statistics')
    basic_group.add_argument('-c', '--chars', action='store_true', help="Count characters.")
    basic_group.add_argument('-w', '--words', action='store_true', help="Count words.")
    basic_group.add_argument('-s', '--sentences', action='store_true', help="Count sentences.")
    basic_group.add_argument('--all', action='store_true', help="Show all basic statistics.")
    extended_group = parser.add_argument_group('Extended Code Analysis')
    extended_group.add_argument('-x', '--extended', action='store_true', help="Show all extended statistics.")
    extended_group.add_argument('-l', '--total-lines', action='store_true', help="Show total number of lines.")
    extended_group.add_argument('-cl', '--code-lines', action='store_true', help="Show number of code lines.")
    extended_group.add_argument('-bl', '--blank-lines', action='store_true', help="Show number of blank lines.")
    extended_group.add_argument('-nl', '--comment-lines', action='store_true', help="Show number of comment lines (note lines).")
    args = parser.parse_args()

    try:
        with open(args.file, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
    except FileNotFoundError:
        #智能建议逻辑
        print(f"File Error: File not found at {args.file}", file=sys.stderr)
        
        try:
            input_path = args.file
            input_dir = os.path.dirname(input_path)
            input_filename = os.path.basename(input_path)
            
            if not input_dir: # 如果用户只输入了文件名，则搜索当前目录
                input_dir = '.'

            if os.path.isdir(input_dir):
                best_match = None
                min_distance = float('inf')
                
                for filename in os.listdir(input_dir):
                    distance = levenshtein_distance(input_filename, filename)
                    if distance < min_distance:
                        min_distance = distance
                        best_match = filename
                
                # 如果最小编辑距离小于等于3，我们认为这是一个可能的拼写错误
                if best_match and min_distance <= 3:
                    suggested_path = os.path.join(input_dir, best_match)
                    print(f"Did you mean: {suggested_path}?", file=sys.stderr)
        except Exception:
            #如果在寻找建议的过程中出错，就静默失败，不影响主错误信息
            pass

        sys.exit(1)

    is_basic = args.all or args.chars or args.words or args.sentences
    is_extended = args.extended or args.total_lines or args.code_lines or args.blank_lines or args.comment_lines
    if is_extended:
        results = analyze_code_content(content, args.file)
        if args.extended or args.total_lines: print(f"Total Lines: {results['total']}")
        if args.extended or args.code_lines: print(f"Code Lines: {results['code']}")
        if args.extended or args.blank_lines: print(f"Blank Lines: {results['blank']}")
        if args.extended or args.comment_lines: print(f"Comment Lines: {results['comment']}")
    elif is_basic:
        if args.all or args.chars: print(f"Characters: {count_chars(content)}")
        if args.all or args.words: print(f"Words: {count_words(content)}")
        if args.all or args.sentences: print(f"Sentences: {count_sentences(content)}")
    else:
        parser.print_help()


if __name__ == '__main__':
    main()